from flask import Blueprint,request,make_response,jsonify,redirect
import json, random, time, requests
from utils.myredis import r
from models.models import *

left_blue = Blueprint("leftblue",__name__)

@left_blue.route("/getkind")
# 获取顶级父类
def getkind():
    kinds = db.session.execute("select b.*,a.name as pname,a.id as pid from kind as a left join kind as b on a.id=b.type where a.type=0")
    kind_lst = []
    idss = []
    kinds = list(kinds)
    if kinds:
        for i in kinds:
            # 判断父类是否存在，不存在添加
            if i.pname not in idss:
                idss.append(i.pname)
                kind_lst.append({
                    "id":i.pid,
                    "name":i.pname,
                    "son":[{
                        "name":i.name,
                        "id":i.id,
                        "type":i.type
                    }]
                })
            else:
                # 存在，查找父类，遍历父类用子类的pid对比
                for (index,p) in enumerate(kind_lst):
                    if i.pid == p["son"][0]["type"]:
                        # 将子类加到父类下
                        kind_lst[index]['son'].append({"id": i.id, "name": i.name})
    return jsonify({"code": 200, "msg": "获取成功","data":kind_lst})

@left_blue.route("/getclose")
# 支付方式
def getclose():
    close = Close.query.all()
    print(close)
    lst = []
    for i in close:
        lst.append({
            "id":i.id,
            "name":i.name,
            "described":i.described
        })
    return jsonify({"code": 200, "msg": "获取成功","data":lst})

@left_blue.route("/getneed")
# 获取需求/人才
def getneed():
    label = Need_kind.query.all()
    lists = []
    list_one = []
    for i in label:
        # 获取所有pid==0的数据
        if i.pid == 0:
            # 判断时候在list_one列表中
            if i.id not in list_one:
                # 将pid==0的数据加入到lists总
                lists.append({'id':i.id,'name':i.name,'son':[]})
                list_one.append([i.id])
    for j in label:
        for index,p in enumerate(lists):
            # 判断所有数据的pid是否等于lists中的id，将等于的数据加入到lists中的son中
            if j.pid == p['id']:
                lists[index]['son'].append({'id':j.id,'name':j.name,'tow_son':[]})
    for s in label:
        for index,p in enumerate(lists):
            aa = lists[index]['son']
            for indexa,a in enumerate(aa):
                if s.pid == a['id']:
                    aa[indexa]['tow_son'].append({'id':s.id,'name':s.name})
    return jsonify({"code":200,"data":lists})








